package com.etime.yqtsponsor.controller;

import com.etime.yqtsponsor.common.BaseMessage;
import com.etime.yqtsponsor.dto.VoteRegisterDto;
import com.etime.yqtsponsor.dto.VoteRegisterDtos;
import com.etime.yqtsponsor.pojo.*;
import com.etime.yqtsponsor.service.ActiveThemeService;
import com.etime.yqtsponsor.service.VoteRegisterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: LouisLew
 * @date: 2022/07/19/16:30
 * @description: 活动信息的控制层
 */
@Api(tags = "活动信息管理的数据接口")
@RestController
@RequestMapping("/active/theme")
public class ActiveThemeController {

    @Autowired
    private ActiveThemeService activeThemeService;
    @Autowired
    private VoteRegisterService voteRegisterService;

    @ApiOperation("添加活动：问卷调查")
    @GetMapping("/createSurveyActiveTheme")
    @ResponseBody
    public BaseMessage createSurveyActiveTheme(ActiveTheme activeTheme, ActivePicBank activePicBanks, Questions questions, SurveyItem surveyItem) {
        int active = activeThemeService.addActiveTheme(activeTheme, activePicBanks, questions, surveyItem);
        BaseMessage baseMessage = new BaseMessage();
        if (active > 0) {
            baseMessage.setCode(1);
            baseMessage.setMsg("创建成功");
        }
        return baseMessage;
    }

    @ApiOperation("添加活动：投票中选手参与活动发表作品")
    @GetMapping("/createVoteRegister")
    public BaseMessage createVoteRegister(VoteRegister voteRegister) {
        BaseMessage baseMessage = new BaseMessage();
        int vote = activeThemeService.addActiveVoteRegister(voteRegister);
        if (vote > 0) {
            baseMessage.setCode(1);
            baseMessage.setMsg("创建成功");
        }
        return baseMessage;
    }


    @ApiOperation("查询历史题目")
    @GetMapping("/findHistoryQuestion")
    //需要接收前端传来的type createdid
    public BaseMessage findHistoryQuestion(int createdId) {
        BaseMessage baseMessage = new BaseMessage();
        List<Questions> history = activeThemeService.findHistoryQuestionById(createdId);
        if (history.size() > 0) {
            baseMessage.setCode(1);
            baseMessage.setMsg("查询成功");
        }
        return baseMessage;
    }
    @ApiOperation("选手所需信息添加")
    @GetMapping("/addActiveVoteForm")
    public BaseMessage addActiveVoteForm(ActiveVoteForm activeVoteForm){
        BaseMessage baseMessage = new BaseMessage();
        int form = activeThemeService.addActiveVoteForm(activeVoteForm);
        if (form > 0) {
            baseMessage.setCode(1);
            baseMessage.setMsg("查询成功");
        }
        return baseMessage;
    }


    @ApiOperation("投票数据导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "当前活动id 必传"),
            @ApiImplicitParam(name = "currentUserId", value = "当前操作人id 必传"),
    })
    @GetMapping("/exportvote")
    public void exportVoteData(ActiveTheme activeTheme, Integer currentUserId, HttpServletResponse response) {
//        BaseMessage msg = new BaseMessage();
//        msg.setCode(0);
        //数据处理逻辑
        Integer activeId = activeTheme.getId();
        if (activeId != null) {
            ActiveTheme nowActiveTheme = activeThemeService.selectById(activeId);
//            if (nowActiveTheme != null && nowActiveTheme.getDeleted() == 0) {
//                if (nowActiveTheme.getCreatedUserId().equals(currentUserId)) {
            String activeTitle = nowActiveTheme.getTitle();
            String activeType = nowActiveTheme.getType();
            List<VoteRegisterDto> list = voteRegisterService.selectExportVote(activeId);
            // excel导出逻辑
            HSSFWorkbook workbook = new HSSFWorkbook();
            //工作表
            HSSFSheet sheet = workbook.createSheet("报名详情");
            //文件名
            SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = format1.format(System.currentTimeMillis());
            String fileName = activeTitle + date + "导出";
            //新增数据行，并且设置单元格数据
            int rowNum = 1;
            String[] headers = {"活动名称", "活动组别", "作品名称", "作品介绍", "展示图", "作品展示", "参赛信息", "总得票数", "普通得票", "广告得票", "积分得票", "报名时间"};
            HSSFRow row = sheet.createRow(0);
            //添加表头
            for (int i = 0; i < headers.length; i++) {
                HSSFCell cell = row.createCell(i);
                HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                cell.setCellValue(text);
            }
            //数据放入对应列
            if (Objects.equals(activeType, "video_vote")) {
                for (VoteRegisterDto vrd : list) {
                    HSSFRow newRow = sheet.createRow(rowNum);
                    newRow.createCell(0).setCellValue(activeTitle);
                    newRow.createCell(1).setCellValue(vrd.getName());
                    newRow.createCell(2).setCellValue(vrd.getTitle());
                    newRow.createCell(3).setCellValue(vrd.getDesc());
                    newRow.createCell(4).setCellValue(vrd.getShowPic());
                    newRow.createCell(5).setCellValue(vrd.getVideoUrl());
                    newRow.createCell(6).setCellValue(vrd.getFormContent());
                    newRow.createCell(7).setCellValue(vrd.getTotalVote());
                    newRow.createCell(8).setCellValue(vrd.getNormalVote());
                    newRow.createCell(9).setCellValue(vrd.getAdVote());
                    newRow.createCell(10).setCellValue(vrd.getScoreVote());
                    newRow.createCell(11).setCellValue(format2.format(vrd.getCreatedTime()*1000L));
                    rowNum++;
                }
            }
            if (activeType == "vote") {
                for (VoteRegisterDto vrd : list) {
                    HSSFRow newRow = sheet.createRow(rowNum);
                    newRow.createCell(0).setCellValue(activeTitle);
                    newRow.createCell(1).setCellValue(vrd.getName());
                    newRow.createCell(2).setCellValue(vrd.getTitle());
                    newRow.createCell(3).setCellValue(vrd.getDesc());
                    newRow.createCell(4).setCellValue(vrd.getShowPic());
                    newRow.createCell(5).setCellValue(vrd.getPicIds());
                    newRow.createCell(6).setCellValue(vrd.getFormContent());
                    newRow.createCell(7).setCellValue(vrd.getTotalVote());
                    newRow.createCell(8).setCellValue(vrd.getNormalVote());
                    newRow.createCell(9).setCellValue(vrd.getAdVote());
                    newRow.createCell(10).setCellValue(vrd.getScoreVote());
                    newRow.createCell(11).setCellValue(format2.format(vrd.getCreatedTime()));
                    rowNum++;
                }
            }
            try {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1 )+ ".xls");
                response.flushBuffer();
                workbook.write(response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
//                        msg.setMsg("导出错误");
//                } else {
//                    msg.setMsg("未拥有操作选手信息权限");
//                }
//            } else {
//                msg.setMsg("活动不存在");
//            }
//        }
//        return msg;
        }
    }

    @ApiOperation("表单&问卷数据导出(按用户区分)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "当前活动id 必传"),
            @ApiImplicitParam(name = "currentUserId", value = "当前操作人id 必传"),
    })
    @GetMapping("/exportform")
    public void exportFormData(ActiveTheme activeTheme, Integer currentUserId, HttpServletResponse response) {
        Integer activeId = activeTheme.getId();
        if (activeId != null) {
            ActiveTheme nowActiveTheme = activeThemeService.selectById(activeId);
            String activeTitle = nowActiveTheme.getTitle();
            String activeType = nowActiveTheme.getType();
            List<VoteRegisterDtos> list = voteRegisterService.selectExportForm(activeId);
            // excel导出逻辑
            HSSFWorkbook workbook = new HSSFWorkbook();
            //工作表
            HSSFSheet sheet = workbook.createSheet("活动详情");
            //文件名
            SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = format1.format(System.currentTimeMillis());
            String fileName = activeTitle + date + "导出";
            //新增数据行，并且设置单元格数据
            int rowNum = 1;
            String[] headers = {"活动名称", "名称", "参与信息", "题目", "答案", "参与时间"};
            HSSFRow row = sheet.createRow(0);
            //添加表头
            for (int i = 0; i < headers.length; i++) {
                HSSFCell cell = row.createCell(i);
                HSSFRichTextString text = new HSSFRichTextString(headers[i]);
                cell.setCellValue(text);
            }
            //数据放入对应列
            for (VoteRegisterDtos vrds : list) {
                HSSFRow newRow = sheet.createRow(rowNum);
                newRow.createCell(0).setCellValue(activeTitle);
                newRow.createCell(1).setCellValue(vrds.getTitle());
                newRow.createCell(2).setCellValue(vrds.getFormContent());
                newRow.createCell(3).setCellValue(vrds.getAnswers());
                newRow.createCell(4).setCellValue(vrds.getAnswers());
                newRow.createCell(5).setCellValue(format2.format(vrds.getCreatedTime() * 1000L));
                rowNum++;
            }
            try {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + ".xls");
                response.flushBuffer();
                workbook.write(response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
